import React from "react"
import {connect} from "react-redux";
import configureStore from 'stores'
import { setApproveRequestSelected } from 'actions/cache'
import { Affix, message } from 'antd'
import menuRoute from 'routes/menuRoute'
import 'styles/approve/request/approve-request-quick-view.scss'
import {messages} from "share/common";
import approveService from 'containers/approve/approve.service'
import WaterfallBox from "components/template/waterfall-box/waterfall-box"
import ApproveBar from 'components/template/approve-bar'

class ApproveRequestQuickView extends React.Component{
  constructor(){
    super();
    this.state = {
      loading: true,
      passLoading: false,
      rejectLoading: false,
      data: [],
      pagination: {
        pageSize: 20,
        total: 0,
        current: 1,
      },
      page: 0,
      waterfallContent:[
        // {title: "序号", dataIndex: 'index'},
        {title: messages('approve.key63'/*单号*/), dataIndex: 'businessCode', className: 'hide-key lighter half-span'},
        {title: messages('approve.key71'/*提交日期*/), dataIndex: 'submittedDate', dataType: "DATE" , className: 'pull-right lighter'},
        {title: messages('approve.key87'/*单据名称*/), dataIndex: 'formName',className: 'hide-key'},
        {title: messages('approve.key74'/*金额*/), dataIndex: 'amount', dataType: "MONEY", showCode: true, codeIndex:"currencyCode", className: 'hide-key bolder color-yellow'},
        {title: messages('approve.key88'/*本币金额*/), dataIndex: 'baseCurrencyAmount', dataType: "MONEY" ,showCode: true, codeIndex:"baseCurrencyCode", className: 'lighter color-gray'}
      ],
      batchEnabled: false, //是否有批量审批
      selectedRows:[]
    }
    this.approveRequestDetail = menuRoute.getRouteItem('approve-request-detail','key'); //申请单审批详情页
    this.approveExpenseReportDetail = menuRoute.getRouteItem('approve-expense-report-detail', 'key'); //报销单审批详情页
    this.approveLoanDetail = menuRoute.getRouteItem('approve-loan-detail', 'key'); //借款单审批详情页
    this.approveOtherDetail = menuRoute.getRouteItem('approve-other-detail', 'key'); //其他单审批详情页
  }
  componentWillMount() {
    const {page, pagination} = this.state;
    this.setState({
      selectedRows: Array.from(this.props.approveRequestSelected),
    });
    this.getList(page, pagination.pageSize);
  }

  componentDidMount() {
    this.setState({
      selectedRows: this.props.approveRequestSelected || [],
      batchEnabled: this.props.profile['all.Approval.batch.Enable']
    })
  }

  getEntityType = (entityType) => {
    const { profile } = this.props;
    let result = entityType === 1111 ? [] : [entityType];
    if (!result.length) {
      result = [3001, 4001];
      if (!profile['er.opt.approval.disabled']) {
        result.push(1002);
      }
      if (!profile['ca.opt.approval.web.disabled']) {
        result.push(1001);
      }
    }
    return result;
  };

  getList = (page, pageSize) => {
    let data = [];
    let userAvatar = [];
    let nodeOIDList = [];
    let total = 0;
    let resultEntityType = this.getEntityType(1111);
    approveService.getApproveList(false, resultEntityType, page, pageSize).then(res => {
      res.data.map((item, index) => {
        if(userAvatar.indexOf(item.applicant.userOID) === -1){
          userAvatar.push(item.applicant.userOID);
        }
        data.push(item);
      });
      total = res.headers['x-total-count'];
    }).then(() => {
      //拼接头像
      let userAvatarMap = new Map();
      approveService.getUserAvatar(userAvatar.join(",")).then(response => {
        response.data.map((item) => {
          userAvatarMap.set(item.userOID, item.avatar);
        });
        data.map((item) => {
          item.applicant.avatar = userAvatarMap.get(item.applicant.userOID);
        });
        this.setState({
          loading: false,
          data,  //
          page: page +1,
          pagination: {
            total: Number(total) || 0,
            current: page + 1
          }
        });
      });
    })
  };

  //翻页
  onChangePager = (page) => {
    if(page - 1 !== this.state.page)
      this.setState({page: page - 1}, this.getList);
  };

  onChange = (value) => {
    configureStore.store.dispatch(setApproveRequestSelected(value));
    this.setState({
      selectedRows:value
    });
  };

  handleClick = (value) => {
    let formOID = value.split(",")[0];
    let entityOID = value.split(",")[1];
    let approverOID = value.split(",")[2];
    let entityType = value.split(",")[4];
    let url = '';
    switch (entityType) {
      case '1001'://申请单
        url = this.approveRequestDetail.url.replace(':formOID', formOID).replace(':applicationOID', entityOID);
        url += `?approving=true&approverOID=${approverOID}&backUrlKey=approve-request-quick-view`;
        this.context.router.push(url);
        break;
      case '1002'://报销单
        url = this.approveExpenseReportDetail.url.replace(':expenseReportOID', entityOID);
        url += `?approvePending=true&approverOID=${approverOID}&backUrlKey=approve-request-quick-view`;
        this.context.router.push(url);
        break;
      case '3001'://借款单
        url = this.approveLoanDetail.url.replace(':formOID', formOID).replace(':loanBillOID', entityOID).replace(':backType', 'history');
        url += `?approving=true&approverOID=${approverOID}&backUrlKey=approve-request-quick-view`;
        this.context.router.push(url);
        break;
      case '4001'://其他
        url = this.approveOtherDetail.url.replace(':formOID', formOID).replace(':entityOID', entityOID).replace(':backType', 'history');
        url += `?approving=true&approverOID=${approverOID}&backUrlKey=approve-request-quick-view`;
        this.context.router.push(url);
        break;
    }
  };

  //审批操作
  handleApprove = (value, type) => {
    let entities = [];
    const {selectedRows, page, pagination:{pageSize}} = this.state;
    selectedRows.map(item => {
      let paramsObj = {};
      paramsObj.approverOID = item.split(",")[2];
      paramsObj.entityOID = item.split(",")[3];
      paramsObj.entityType = item.split(",")[4];
      entities.push(paramsObj)
    });

    let params = {
      entities,
      approvalTxt: value
    };
    this.setState({[type === 'pass' ? 'passLoading' : 'rejectLoading']: true});
    approveService[type === 'pass' ? 'handleRequestApprovePass' : 'handleRequestApproveReject'](params).then(res => {
      if (res.status === 200) {
        if( res.data.successNum === 0){
          message.error(messages('approve.key109',{arg1:res.data.successNum}/*成功处理 {arg1} 笔单据*/)+', '+
            messages('approve.key110',{arg1:res.data.failNum}/*失败 {arg1} 笔单据*/));
          message.error(JSON.stringify(res.data.failReason));
          this.setState({
            passLoading: false,
            rejectLoading: false,
          });
        }else{
          if( res.data.failNum === 0){
            message.success(messages('approve.key109',{arg1:res.data.successNum}/*成功处理 {arg1} 笔单据*/)+', '+
        messages('approve.key110',{arg1:res.data.failNum}/*失败 {arg1} 笔单据*/));
          }else{
            message.warning(messages('approve.key109',{arg1:res.data.successNum}/*成功处理 {arg1} 笔单据*/)+', '+
        messages('approve.key110',{arg1:res.data.failNum}/*失败 {arg1} 笔单据*/));
            message.error(JSON.stringify(res.data.failReason));
          }

          //如果存在处理成功的数据
          //要把处理成功的数据id从redux中拿掉,failReason里返回的数据是formOID，对应selectedRows中的第二个字段即item.split(",")[1]
          let failArray = Object.keys(res.data.failReason);
          let filterArray = [];
          selectedRows.map((item) => {
            if(failArray.indexOf(item.split(",")[1]) > -1){ //如果是失败的 保留
              filterArray.push(item);
            }
          });
          configureStore.store.dispatch(setApproveRequestSelected(filterArray));
          this.setState({
            passLoading: false,
            rejectLoading: false,
            page: 0,
            pagination: { total: 0 },
            selectedRows: filterArray,
          },() => {
            this.getList(0, pageSize)
          })
        }
      }
    }).catch(e => {
      this.setState({ passLoading: false, rejectLoading: false });
      message.error(`${messages('common.operate.filed'/*操作失败*/)}，${e.response.data.message}`)
    })
  };

  render(){
    const { pagination, selectedRows, data, loading, waterfallContent, passLoading, rejectLoading, batchEnabled } = this.state;
    return(
      <div className="approve-request-quick-view" >
        <div className="box bottom-100">
          <WaterfallBox
            backUrlKey={"to-be-approve"}
            backTitle={messages('approve.key113')/*退出快速查看*/}
            getList={(page,pageSize) => this.getList(page,pageSize)}
            onChange={(value) => this.onChange(value)}
            handleClick={(value) => this.handleClick(value)}
            selectedRows={selectedRows}
            data={data}
            valueKey={"formOID,entityOID,approverOID,entityOID,entityType"}
            pagination={pagination}
            pageSize={pagination.pageSize}
            title={"MATA"}
            MetaTitle={"applicant.fullName"}
            MetaSrc={"applicant.avatar"}
            MetaDescription={"employeeID"}
            MetaClassName={"compact"}
            description={"title"}
            checkable={batchEnabled}
            content={waterfallContent}
          />
        </div>
        <Affix offsetBottom={0} className={`bottom-bar-approve ${selectedRows.length>0 ? 'show' : 'hide'}`}>
          <ApproveBar passLoading={passLoading}
                      rejectLoading={rejectLoading}
                      batchNumber={selectedRows.length}
                      handleApprovePass={value => this.handleApprove(value, 'pass')}
                      handleApproveReject={value => this.handleApprove(value, 'reject')}/>
        </Affix>
      </div>
    )
  }
}
ApproveRequestQuickView.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    approveRequestSelected: state.cache.approveRequestSelected
  }
}
export default connect(mapStateToProps)(ApproveRequestQuickView);
